package com.demo.java8.lambda;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * Created by churcy on 2018/3/21.
 */
public class TestLambda {

    public List<Apple> filterApple(List<Apple> inventory, ApplePredicate applePredicate) {
        List<Apple> result = new ArrayList<Apple>();

        for (Apple apple : inventory) {

            if (applePredicate.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }

    //匿名内部类


    public static void main(String[] args) {

        //初始化apple篮子
        List<Apple> inventory = new ArrayList<Apple>();

        Apple appleGreen = new Apple();
        appleGreen.setColor("green");
        appleGreen.setWeight(50);

        Apple appleHeavy = new Apple();
        appleGreen.setColor("red");
        appleHeavy.setWeight(350);

        Apple appleAnother = new Apple();
        appleAnother.setColor("yellow");
        appleAnother.setWeight(180);

        inventory.add(appleHeavy);
        inventory.add(appleGreen);
        inventory.add(appleAnother);

        TestLambda t = new TestLambda();


        /**
         * 初识Lambda
         */
        //1.筛选apple(策略模式)

        //筛选绿色apple
        AppleGreenPredicate appleGreenPredicate = new AppleGreenPredicate();
        t.filterApple(inventory, appleGreenPredicate);

        //筛选重的apple
        AppleHeavyPredicate appleHeavyPredicate = new AppleHeavyPredicate();
        t.filterApple(inventory, appleHeavyPredicate);

        //2.筛选apple（内部类）

//        //筛选绿色apple
//        t.filterApple(inventory, new ApplePredicate() {
//            public boolean test(Apple apple) {
//                return "green".equals(apple.getColor());
//            }
//        });
//
//        //筛选重的apple
//        t.filterApple(inventory, new ApplePredicate() {
//            public boolean test(Apple apple) {
//                return apple.getWeight() > 150;
//            }
//        });

        //3.筛选apple（Lambda表达式）

        //筛选绿色apple
        t.filterApple(inventory, (Apple apple) -> "green".equals(apple.getColor()));

        //筛选重的apple
        t.filterApple(inventory, (Apple apple) -> apple.getWeight() > 150);

        /**
         * 简单示例
         */
//
//        for (Apple apple : inventory) {
//            System.out.println(apple.getWeight());
//        }
//
//        inventory.sort(new Comparator<Apple>() {
//            @Override
//            public int compare(Apple o1, Apple o2) {
//                return o2.getWeight() + "".compareTo(o1.getWeight() + "");
//            }
//        });

        inventory.sort((Apple o1,Apple o2) -> o2.getWeight() + "".compareTo(o1.getWeight() + ""));

        for (Apple apple : inventory) {
            System.out.println(apple.getWeight());
        }

        Thread thred = new Thread(() -> System.out.println("this is runnable!"));

        thred.run();
    }
}
